'use strict';

// import {FormData} from 'react-native';
// import DeviceInfo from 'react-native-device-info';
import {Toast,ModalIndicator} from 'teaset';

let Util = {
    /**
     * http get 请求简单封装
     * @param url 请求的URL
     * @param successCallback 请求成功回调
     * @param failCallback 请求失败回调
     */
    get: (url, successCallback, failCallback) => {
        // console.log("request get",{url:url});
        fetch(url)
            .then((response) => response.text())
            .then((responseText) => {
                // console.log('responseText:'+responseText);
                let result = JSON.parse(responseText);
                successCallback(result.status, result.code, result.message, result.data, result.share);
            })
            .catch((err) => {
                Toast.message('网络异常');
                ModalIndicator.hide();
                console.log("fetch  url ["+url+"] error:" + err);
                console.log("fetch-failCallback:",failCallback);
                failCallback(err);
            });
    },

    /**
     * http post 请求简单封装
     * @param url 请求的URL
     * @param data post的数据
     * @param successCallback 请求成功回调
     * @param failCallback failCallback 请求失败回调
     */
    post: (url, data, successCallback, failCallback) => {
        
        let formData = new FormData();
        Object.keys(data).map(function(key) {
            var value = data[key];
            formData.append(key, value);
        });
        // console.log("request post",{url:url,post:data});

        let fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',// 'Content-Type': 'application/json'
            },
            body: formData
        };

        // let tmpUrl=url;
        // for (var xx in formData) {
        //     if(formData[xx]!=undefined&&formData[xx]!='')
        //     tmpUrl+='/'+xx+'/'+formData[xx];
        // }
        // console.log('tmpUrl:'+tmpUrl);

        let debug='';
        let dd=true;
        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                if(dd)debug=responseText;
                let result = JSON.parse(responseText);
                successCallback(result.status, result.code, result.message, result.data, result.share);
            })
            .catch((err) => {
                Toast.message('网络异常');
                ModalIndicator.hide();
                if(dd)console.log("post debug:",debug);
                console.log('failCallback',failCallback);
                console.log('failCallback-err',err);
                failCallback("post errorB:["+url+"]["+err+"]");
            });
    },
    /**
     * http get 请求简单封装
     * @param url 请求的URL
     * @param successCallback 请求成功回调
     * @param failCallback 请求失败回调
     */
    getHTML: (url, successCallback, failCallback) => {
        fetch(url)
            .then((response) => response.text())
            .then((responseText) => {
                // console.log("post responseText:["+url+"]["+responseText+"]");
                successCallback(responseText);
            })
            .catch((err) => {
                Toast.message('网络异常');
                ModalIndicator.hide();
                console.log("fetch  url ["+url+"] error:" + err);
                failCallback(err);
            });
    },



    /**
     * 日志打印
     * @param obj
     */
    log: (obj) => {
        var description = "";
        for(let i in obj){
            let property = obj[i];
            description += i + " = " + property + "\n";
        }
        alert(description);
    },




    /** 校验身份证号码 */
    verifyIdNo:(id) => {
        // console.log('verifyIdNo:',id);
     // 1 "验证通过!", 0 //校验不通过
        var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
        //号码规则校验
        if(!format.test(id)){
            // console.log('id:'+id);
            return {'status':0,'msg':'身份证号码不合规'};
        }
        //区位码校验
        //出生年月日校验   前正则限制起始年份为1900;
        var year = id.substr(6,4),//身份证年
            month = id.substr(10,2),//身份证月
            date = id.substr(12,2),//身份证日
            time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
            now_time = Date.parse(new Date()),//当前时间戳
            dates = (new Date(year,month,0)).getDate();//身份证当月天数
        if(time>now_time||date>dates){
            return {'status':0,'msg':'出生日期不合规'}
        }
        //校验码判断
        var c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);   //系数
        var b = new Array('1','0','X','9','8','7','6','5','4','3','2');  //校验码对照表
        var id_array = id.split("");
        var sum = 0;
        for(var k=0;k<17;k++){
            sum+=parseInt(id_array[k])*parseInt(c[k]);
        }
        if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
            return {'status':0,'msg':'身份证校验码不合规'}
        }
        return {'status':1,'msg':'校验通过'}
    },
    hasKey:(obj,key) => {
        let ret;
        let exists=false;
        for (var kk in obj) 
        {
            if(key==kk){
                exists=true;
                break;
            }
        }
        return exists;
    },
    in_array:(obj,arr) => {
        let result=false;
        for (var i = 0; i < arr.length; i++) {
            if(obj==arr[i])
            {
                result=true;
                break;
            }
        }
        return result;
    },

    /**
        获取设备信息
    */
   /* getDeviceInfo:() => {
        return {UniqueID:DeviceInfo.getUniqueID(),
                Manufacturer:DeviceInfo.getManufacturer(),
                Brand:DeviceInfo.getBrand(),
                Model:DeviceInfo.getModel(),
                DeviceId:DeviceInfo.getDeviceId(),
                SystemName:DeviceInfo.getSystemName(),
                SystemVersion:DeviceInfo.getSystemVersion(),
                BundleId:DeviceInfo.getBundleId(),
                BuildNumber:DeviceInfo.getBuildNumber(),
                Version:DeviceInfo.getVersion(),
                ReadableVersion:DeviceInfo.getReadableVersion(),
                DeviceName:DeviceInfo.getDeviceName(),
                UserAgent:DeviceInfo.getUserAgent(),
                DeviceLocale:DeviceInfo.getDeviceLocale(),
                DeviceCountry:DeviceInfo.getDeviceCountry(),
                Timezone:DeviceInfo.getTimezone(),
                Emulator:DeviceInfo.isEmulator(),
                Tablet:DeviceInfo.isTablet()};;
    },*/

/**
    初始输入参数，主要用途为，当表单有默认的输入数据时候，因用户没有修改值，则不会反应到state.formItems中，所以需要先将表单的初始数据存储进入该state中
*/

_initFormItems:(checkItems) => {
    let formItem={};
    for (var i = 0; i < checkItems.length; i++) 
    {
        if(checkItems[i].defaultValue)
        {
            if(checkItems[i].type!=undefined&&checkItems[i].type=='checkbox')
            {
                if(formItem[checkItems[i].code]==undefined||formItem[checkItems[i].code]=="")
                {
                    formItem[checkItems[i].code]=[checkItems[i].defaultValue];
                }else{
                    formItem[checkItems[i].code].push(checkItems[i].defaultValue);
                }
            }else{
                formItem[checkItems[i].code]=checkItems[i].defaultValue;
            }            
        }

    }
    return formItem;
}


};

export default Util;